package com.codeoss.framework.springsecurity;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.module.res.model.ResRole;
import com.codeoss.module.res.model.ResUser;
import com.codeoss.module.res.service.IResRelUserRoleService;
import com.codeoss.module.res.service.IResRoleService;
import com.codeoss.module.res.service.IResUserService;

public class MiUserDetailsService implements UserDetailsService {
    @Autowired
    private IResUserService resUserService;
    @Autowired
    private IResRelUserRoleService resRelUserRoleService;
    @Autowired
    private IResRoleService resRoleService;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		QueryWrapper<ResUser> query=new QueryWrapper<ResUser>();
		query.eq("username", username);
		ResUser resUser=resUserService.getOne(query);
		List<Long> roleIdList=resRelUserRoleService.getRoleIdListByUserId(resUser.getId());
		QueryWrapper<ResRole> roleQuery=new QueryWrapper<ResRole>();
		roleQuery.in("id", roleIdList);
		List<ResRole> roleList=resRoleService.list(roleQuery);
		List<GrantedAuthority> roleGrantedAuthorityList=new ArrayList<GrantedAuthority>();
		for(int i=0;i<roleList.size();i++) {
			roleGrantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_"+roleList.get(i).getCode()));
		}
		JwtUser jwtUser=new JwtUser(resUser,roleGrantedAuthorityList);
		return jwtUser;
	}

}
